
//
//  HMStatusPictureView.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/9/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let itemMargin : CGFloat = 5
// 确定每一个条目的宽高
private let itemHW = (HMScreenW - 2*HMStatusCellMargin - 2*itemMargin)/3

class HMStatusPictureView: UICollectionView {
    
    
    let HMPictureViewCellId = "cell"
    
    // 当前配图视图显示的配图数据
    var pic_urls: [HMStatusPictureInfo]? {
        didSet{
//            label.text = "\(pic_urls?.count ?? 0)"
            
            // 要根据图片的数量去设置当前配图控件的大小
            self.snp_updateConstraints { (make) in
                make.size.equalTo(calcSize(count: pic_urls?.count ?? 0))
            }
//
            self.reloadData()
            print(label.text)

        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        // 注册cell
        self.register(HMPicturViewCell.self, forCellWithReuseIdentifier: HMPictureViewCellId)
        // 自己成为自己的数据源
        self.dataSource = self
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 要设置条目的大小
        layout.itemSize = CGSize(width: itemHW, height: itemHW)
        // 设置行间距与列间距
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
        // 添加label
//        addSubview(label)
        // 添加约束
//        label.snp_makeConstraints { (make) in
//            make.center.equalTo(self)
//        }
        
    }

    /// 通过传入的count，计算配图视图的大小
    ///
    /// - parameter count: <#count description#>
    func calcSize(count:Int) -> CGSize {
        if count == 1 {
            // 要取到这一张图片的在大小
            // 如何取到之前下载的图片？
            if let size = pic_urls?.first?.size {
                let scale = UIScreen.main.scale
                // 通过屏幕比例计算出真实的大小
                let result = CGSize(width: scale * size.width, height: scale * size.height)
                // 调用itemSize的大小
                // 1. 取到layout
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = result
                
                // 2. 调整配图控件的大大小
                return result
            }

        }
        
        // 要确定有多少列
        var col = count > 3 ? 3:count
        if count == 4 {
            col = 2
        }
        // 要确定有多少行
        let row = (count - 1) / 3 + 1
        
        // 通过列数、行数与每一列的宽高计算大小
        let width = CGFloat(col) * itemHW + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemHW + CGFloat(row - 1) * itemMargin
        
        let size = CGSize(width: width, height: height)
        
        // 如果是多张图片，要调条目的大小调整回来
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 调条目大小调整成正方形
        layout.itemSize = CGSize(width: itemHW, height: itemHW)
        return size
    }
    
    
    
     //MARK: - 懒加载控件
    
    private lazy var label: UILabel = {
        let lable = UILabel(textColor: UIColor.black, fontSize: 30)
        return lable
    }()


}


// MARK: - 数据源方法
// 在 Xcode 8之前，extension中可以使用原类中的私有变量
// 在 Xcode 8 之后，就不可以了

extension HMStatusPictureView : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 从缓存中去取到对应位置的cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMPictureViewCellId, for: indexPath) as! HMPicturViewCell
        // 1. 取到模型
        let model = pic_urls![indexPath.row]
        // 2. 设置给cell
        cell.pictureInfo = model
//        let color : UIColor = UIColor(red: CGFloat(arc4random()%256)/255, green: CGFloat(arc4random()%256)/255, blue: CGFloat(arc4random()%256)/255, alpha: 1)
//        cell.backgroundColor = color
        return cell
        
        
        
    }
    
    }




class HMPicturViewCell: UICollectionViewCell {
    // 当前cell对应的模型
    var pictureInfo : HMStatusPictureInfo?{
        didSet{
            // 让imageView显示图片
            imageView.sd_setImage(with:URL(string:pictureInfo?.thumbnail_pic ?? ""),placeholderImage:UIImage(named: "timeline_image_placeholder"))
        }
    }
//
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//
    private func setupUI(){
        // 添加子控件
        addSubview(imageView)
        // 添加约束
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
    }
//
    // MARK: - 懒加载控件
    lazy var imageView:UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
//
//    
}
